<template>
  <div class="video-container">
    <input type="file" ref="fileRef" class="file-input" @change="selectFile" />
    <el-button mr10 type="primary" @click="handleClickFile" mt20 ml20
      >上传文件</el-button
    >
    <div class="video-part">
      <video :src="videoSrc" h-full w-full controls></video>
      <ul>
        <li v-for="item in imgList" mr10 @click="previewImg(item)" title="预览">
            <img :src="item" alt="img">
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";

const fileRef = ref<HTMLInputElement>();

const handleClickFile = () => {
  fileRef.value?.click();
};

const file = ref<File>();
const videoSrc = ref("");
const selectFile = (e: any) => {
  file.value = e.target?.files[0];
  videoSrc.value = URL.createObjectURL(e.target?.files[0]);
  showFrameImg(8)
};

const imgList = ref<string[]>([])
const showFrameImg = async (time:number) => {
    for(let i = 0 ;i<time;i++){
        const {src,blob} = await captureFrame(file.value as File,i)
        imgList.value.push(src)
    }
}

const previewImg = (img:string) => {
    window.open(img)
}

/**
 * 截取当前时间的视频帧，返回图片
 * @param videoFile 视频文件
 * @param time 时间
 */
const captureFrame = (videoFile: File, time: number = 0) => {
  return new Promise<{src:string,blob:Blob}>((resolve) => {
    const vdo = document.createElement("video");
    vdo.src = URL.createObjectURL(videoFile);
    vdo.currentTime = time;
    vdo.muted = true;
    vdo.autoplay = true;
    vdo.oncanplay = (e: Event) => {
      const canvas = document.createElement("canvas");
      canvas.width = vdo.videoWidth;
      canvas.height = vdo.videoHeight;
      const ctx = canvas.getContext("2d");
      ctx?.drawImage(vdo, 0, 0, canvas.width, canvas.height);
      canvas.toBlob((blob) => {
        const src = URL.createObjectURL(blob as Blob);
        resolve({
          src,
          blob:blob as Blob
        });
      });
    };
  });
};
</script>

<style scoped lang="scss">
.video-container {
  .file-input {
    display: none;
  }

  .video-part {
    width: 800px;
    margin: 20px auto;

    ul{
        list-style: none;
        display: flex;
        padding: 0;
        li{
            cursor: pointer;
            img{
                width: 100px;
            }
        }
    }
  }
}
</style>
